package eaxm;

import java.util.Arrays;

/**
 * @Auther:小陈的Java
 * 定义用户，根据自然排序给用户按照年龄升序排序
 */
public class Number13 {
    public static void main(String[] args) {
        //定义user数组，并设置数组元素内容
        User[] users = new User[4];
        for (int i = 0; i <users.length; i++) {
            User user = new User();
            user.setId(i+1);
            user.setName("张三"+(i+1));
            user.setAge((int)(Math.random()*100));
            users[i] = user;
        }
        //排序
        Arrays.sort(users);
        //查看
        System.out.println(Arrays.toString(users));
    }
}
class User implements Comparable{
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        if(o==null){
            throw new NullPointerException("null不能参与排序");
        }
        if(!(o instanceof  User)){
            throw new ClassCastException();
        }
        User user = (User)o;
        return this.age-user.getAge();
    }
}